package edu.gyc.hisecurity.service.impl;

import edu.gyc.hisecurity.dao.MenuDao;
import edu.gyc.hisecurity.model.Menu;
import edu.gyc.hisecurity.model.Role;
import edu.gyc.hisecurity.model.User;
import edu.gyc.hisecurity.dao.UserDao;
import edu.gyc.hisecurity.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;


import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author ls
 * @since 2019-12-06
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserDao, User> implements UserService {

    @Autowired
    UserDao userDao;
@Autowired
    MenuDao menuDao;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user=lambdaQuery().eq(User::getUsername,username).one();
        if (user == null) {
            throw new UsernameNotFoundException("用户名有误！");
        }
        log.info("User: "+user.getUsername()+" want to login.");

        List<Role> roles = userDao.getRolesByUserId(user.getId());
        user.setRoles(roles);

        //查询此登录用户可访问的菜单路径
        List<String> menuList = new ArrayList<>();
        for (Role role : roles) {
            List<Menu>  menus= menuDao.selectMenusByRoleId(role.getId());
            for (Menu menu : menus) {
                menuList.add(menu.getPath());
            }
        }
        log.info(username+" menus:"+menuList);
        user.setLoginUserMenus(menuList);
        log.info("User "+user.getUsername()+" menus: "+user.getLoginUserMenus());
        return user;
    }
}
